// 云函数入口文件 - 根据unionid发送公众号模板消息（本函数逻辑是根据unionid查询用户集合中保存的公众号openid来发送模板消息）
const cloud = require('wx-server-sdk')
const request = require('request')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const tokens = db.collection("token表");
const users = db.collection("用户表");
const template_send_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=';


// 云函数入口函数
exports.main = async (event, context) => {
    var params = event.params;
    if (!params) {
        return 'MISS';
    }
    var unionid = params.unionid;
    var templateid = params.templateid
    if (!unionid || !templateid) {
        return 'MISS';
    }
    // 根据unionid查询公众号的openid
    var userRes = await users.where({
        unionid: _.eq(unionid)
    }).get();
    if (!userRes || !userRes.data || userRes.data.length == 0) {
        return 'MISS';
    }
    var gzh_openid = userRes.data[0].gzh_openid;
    if (!gzh_openid) {
        return 'MISS';
    }
    var accessToken = await getAccessToken();
    if (!accessToken) {
        return 'MISS';
    }
    var body = {
        touser: gzh_openid,
        template_id: templateid
    }
    if (params.url) {
        body.url = url
    } else if (params.appid) {
        body.miniprogram = {
            appid: params.appid,
            pagepath: params.pagepath
        }
    }
    var data = {};
    for (var i = 1; i < 6; i++) {
        var kw = "keyword" + i;
        if (params[kw]) {
            data[kw] = {
                value: params[kw]
            }
        } else {
            break;
        }
    }
    body.data = data;
    // 发送
    var sendRes = await doPost(template_send_url + accessToken, body);
    if (!sendRes.errmsg || sendRes.errmsg != "ok") {
        return 'FAIL';
    }
    return 'OK';
}


async function doPost(url, body) {
    const result = await rp({
        url: url,
        body: body
    });
    return (typeof result.body === 'object') ? result.body : JSON.parse(result.body);
}


async function getAccessToken() {
    const res = await tokens.skip(0).limit(1).orderBy('createTime', 'desc').where({
        type: _.eq('stable_token') // 保存token时的类型，自定义，也可不存
    }).get();
    if (res && res.data && res.data.length == 1) {
        return res.data[0].accessToken;
    }
    return '';
}

const rp = options =>
    new Promise((resolve, reject) => {
        request({
            ...options,
            method: 'POST',
            json: true
        }, (error, response, body) => {
            if (error) {
                reject(error);
            }
            resolve(response);
        });
    });